import { Util } from '@/Util';
import { SocketDataType, SocketEventType } from '@/share/commonType';
import io from 'socket.io-client'
import { Socket } from 'socket.io-client';
import { ClientSocketEventType } from "@/share/commonType";
interface MsgType {
    action: SocketEventType,
    dataType?: SocketDataType,
    data: any
}
interface ClientMsgType {
    action: ClientSocketEventType,
    data: any
}
class SocketIo {
    socket: Socket;
    constructor() {
        this.socket = io(Util.host);
        this.init()
    }
    init() {
        this.heartBounceTest()
        this.on('connect', () => {
            console.log('socket.io 连接成功!')
            this.heartBounceHandler() // 首次连接发一次心跳
        })
        this.on('disconnect', () => {
            console.log('socket.io 断开连接!')
        })
    }
    heartBounceTest() { // 每隔十秒向服务端发送心跳
        setInterval(this.heartBounceHandler, 5000)
    }
    heartBounceHandler = () => {
        let userInfo = localStorage.getItem('zhupm')
        if (userInfo) {
            this.emit({
                action: SocketEventType.HeartBounce,
                data: JSON.parse(userInfo).user.username
            })
        }
    }
    on(eventName: string, callback: (msg: ClientMsgType) => any) {// 监听事件
        this.socket.on(eventName, callback)
    }
    emit(msg?: MsgType) { // 发射事件
        this.socket.emit('msg', msg)
    }
}

export default SocketIo